﻿using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;

namespace Daan
{
    public class WeightedRandom<T>
    {
        public List<(T item, int weight)> list = new List<(T item, int weight)>();

        public void AddRange(List<T> list, Func<T, int> func)
        {
            foreach (var item in list)
            {
                var weight = func(item);
                this.Add(item, weight);
            }
        }

        public void Add(T item, int weight)
        {
            if (weight <= 0)
            {
                return;
            }

            var cumulativeWeight = weight;
            if (this.list.Count > 0)
            {
                cumulativeWeight += this.list[^1].weight;
            }

            this.list.Add((item, cumulativeWeight));
        }

        public T GetRandom()
        {
            if (this.list.Count == 0)
                throw new InvalidOperationException("No items to select from.");

            var randomValue = UnityEngine.Random.Range(0, 1f) * this.list[^1].weight;

            foreach (var (item, cumulativeWeight) in this.list)
            {
                if (randomValue < cumulativeWeight)
                {
                    return item;
                }
            }

            // Should never reach here
            throw new InvalidOperationException("Random selection failed.");
        }
    }
}